const goodModel = require('../../model/good')
const cateModel = require('../../model/cate')

class GoodController {
    static async goodlist(ctx) {
        let { name, cate, page, size, checked } = ctx.request.query
        page = parseInt(page || 1)
        size = parseInt(size || 10)
        let params = {
            name: new RegExp(name, 'img'),
            cate,
            checked,
            status: { $gte: 0 }
        }
        if (!name) delete params.name
        if (!cate) delete params.cate
        if (checked === undefined) delete params.checked

        const total = await goodModel.find(params).count()
        const list = await goodModel.find(params).limit(size).skip((page - 1) * size).sort({ _id: -1 })
        ctx.body = { err: 0, msg: 'success', data: { total, list } }
    }

    // 编辑与新增
    static async goodAddOrEdit(ctx) {
        // id是编辑，没有id是新增
        let { _id, name, desc, price, img, cate, hot } = ctx.request.body
        console.log(ctx.request.body)
        let ele = {
            name,
            desc,
            price,
            img,
            cate
        }
        if (_id) {
            const editinfo = await goodModel.findByIdAndUpdate(_id, ele)
            ctx.body = { err: 0, msg: 'success', data: { editinfo } }
        } else {
            const info = await goodModel.insertMany([ele])
            ctx.body = { err: 0, msg: 'success', data: { info } }
        }
    }

    // 获取所有品类
    static async getAllCate(ctx) {
        const list = await cateModel.find({})
        ctx.body = { err: 0, msg: 'success', data: { list } }
    }

    static async goodCheck(ctx) {
        // 0 -未审核 -1 -已驳回 1 -审核通过
        let { id, checked } = ctx.request.query
        if (checked === undefined) checked = 0
        checked = Number(checked)
        try {
            const info = await goodModel.updateOne({ _id: id }, { $set: { checked } })
            ctx.body = { err: 0, msg: 'success', data: { info } }
        } catch (err) {
            console.log(err)
            ctx.body = { err: 1, msg: 'fail', data: {} }
        }

    }

    // 删除商品
    static async deletegood(ctx) {
        let { id } = ctx.request.body
        // status 1-正常 0-下架 -1 删除
        const info = await goodModel.updateOne({ _id: id }, { $set: { status: -1 } })
        ctx.body = { err: 0, msg: 'success', data: { info } }
    }

}


module.exports = GoodController